package com.yicao.yicaomall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yicao.yicaomall.product.dao.CategoryBrandRelationDao;
import com.yicao.yicaomall.product.entity.CategoryBrandRelationEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yicao.yicaomall.common.utils.PageUtils;
import com.yicao.yicaomall.common.utils.Query;

import com.yicao.yicaomall.product.dao.BrandDao;
import com.yicao.yicaomall.product.entity.BrandEntity;
import com.yicao.yicaomall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 保存并更新关系
     *
     * @param brand 关系实体
     */
    @Override
    @Transactional
    public void saveAndUpdateRelation(BrandEntity brand) {
        this.updateById(brand);
        if (!StringUtils.isEmpty(brand.getName())) {
            categoryBrandRelationDao.update(null,
                    new LambdaUpdateWrapper<CategoryBrandRelationEntity>()
                            .set(CategoryBrandRelationEntity::getBrandName, brand.getName())
                            .eq(CategoryBrandRelationEntity::getBrandId, brand.getBrandId()));
        }
    }


}
